package service

import (
	"database/sql"
	"encoding/json"
	"github.com/e421083458/golang_common/lib"
	"rock/customer/dto"
	"rock/customer/modules/mapping"
	"rock/customer/modules/redisModules"
	"time"
)

// 数据库初始操作
func InitData()  {

}

// 查询多行；查询数据,取所有字段,不采用结构体
func rawQueryAllField(MysqlDb *sql.DB, Sql string) ([]dto.ChatMessagePage, error) {
	//查询数据，取所有字段
	rows2, _ := MysqlDb.Query(Sql)
	//返回所有列
	cols, _ := rows2.Columns()
	//这里表示一行所有列的值，用[]byte表示
	vals := make([][]byte, len(cols))
	//这里表示一行填充数据
	scans := make([]interface{}, len(cols))
	//这里scans引用vals，把数据填充到[]byte里
	for k := range vals {
		scans[k] = &vals[k]
	}
	i := 0
	result := make([]dto.ChatMessagePage, 0)
	//result := make(map[int]map[string]string, 0)
	for rows2.Next() {
		//填充数据
		_ = rows2.Scan(scans...)
		//每行数据
		//row := dto.ChatMessagePage{}
		row := make(map[string]interface{}, 0)
		//把vals中的数据复制到row中
		//fmt.Println(reflect.TypeOf(vals))
		for k, v := range vals {
			key := cols[k]
			//这里把[]byte数据转成string
			row[key] = string(v)
		}
		d := &dto.ChatMessagePage{}
		err := mapping.SlStruct(row, d, 1)
		if err != nil {
			//fmt.Println(fmt.Sprintf("err ==> %v", err))
			return nil, err
		}
		//make(map[string]reflect.Value)
		//放入结果集
		//result[i] = row
		result = append(result, *d)
		i++
	}
	defer func() {
		_ = rows2.Close()
	}()
	return result, nil
}

// 初始化DB
func InitDefaultGormDB() error {

	var err error

	once.Do(func() {
		db, errDb := lib.GetGormPool("default")
		if errDb != nil {
			err = errDb
		}
		InstanceDB = db
		//fmt.Println(fmt.Sprintf("db.DB() => %v", InstanceDB.DB()))
		db2, errDb2 := lib.GetGormPool("business")
		if errDb2 != nil {
			err = errDb2
		}
		BusinessDB = db2
		//fmt.Println(fmt.Sprintf("db.DB() => %v", BusinessDB.DB()))
	})

	return err
}

// 添加缓存
func addRedis(data interface{}, redisKey string, expiration time.Duration) error {
	jsonContent, err := json.Marshal(data)
	if err != nil {
		return err
	}
	result := redisModules.ClientRedis.Set(redisKey, jsonContent, expiration)
	if result.Err() != nil {
		return result.Err()
	}
	return nil
}